using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32;
using System.Reflection;
using System.Xml;
using System.Diagnostics;
using System.Security.Principal;


namespace SPALM.SharePointSoftwareFactory.SetupHelper
{
  public partial class Form1 : Form
  {
    public string htmlPageDir = "";
    private bool elevationRequested = false;

    public Form1()
    {
      InitializeComponent();
      //GetAndDisplayRights();

      try
      {
          licenceStep1.AgreementChanged += new GenericEventHandler<bool>(licenceStep1_AgreementChanged);
          wizardControl1.CurrentStepIndexChanged += new EventHandler(wizardControl1_CurrentStepIndexChanged);
          this.FormBorderStyle = FormBorderStyle.FixedDialog;

          if (!elevationRequested)
          {
              LoadAuthors();
              LoadFileVersion();
          }
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.ToString());
      }
    }    

    private void GetAndDisplayRights()
    {
      WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
      if (!pricipal.IsInRole(WindowsBuiltInRole.Administrator))
      {
        this.Visible = false;
        timer_Closing.Enabled = true;
        elevationRequested = true;
        //this.WindowState = FormWindowState.Minimized;
        ProcessStartInfo processInfo = new ProcessStartInfo();
        processInfo.Verb = "runas";
        processInfo.FileName = Assembly.GetEntryAssembly().Location;
        try
        {
          Process.Start(processInfo);
        }
        catch (Win32Exception)
        {
          //Do nothing. Probably the user canceled the UAC window
        }
      }
    }

    private string GetFileVersion()
    {
      Assembly assembly = Assembly.GetExecutingAssembly();
      FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
      return fvi.ProductVersion;
    }

    private void LoadFileVersion()
    {
      label_Version.Text = GetFileVersion();
    }

    private void LoadAuthors()
    {
      Stream resourceStream = Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("SPALM.SharePointSoftwareFactory.SetupHelper.Authors.xml");
      string authors = "";
      if (resourceStream != null)
      {
        XmlDocument doc = new XmlDocument();
        doc.Load(resourceStream);

        foreach (XmlNode node in doc.SelectNodes("/Authors/Author"))
        {
          if (authors != "")
          {
            authors += ", ";
          }
          authors += node.InnerText;
        }
      }

      textBox_authors.Text = authors;
    }

    void wizardControl1_CurrentStepIndexChanged(object sender, EventArgs e)
    {
      licenseCheck();
      SetVSVersions(this.checkBox_VS2008.Checked, this.checkBox_VS2010.Checked);
    }

    private void SetVSVersions(bool vs2008, bool vs2010)
    {
      this.componentContainer1.SetVSVersions(vs2008, vs2010);
      this.msiContainer1.SetVSVersions(vs2008, vs2010);
    }

    void licenceStep1_AgreementChanged(object sender, GenericEventArgs<bool> tArgs)
    {
      licenseCheck();
    }

    private bool IsInstalled(string productName)
    {
      try
      {
        //The registry key:
        string SoftwareKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
        using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))
        {
          //Let's go through the registry keys and get the info we need:
          foreach (string skName in rk.GetSubKeyNames())
          {
            using (RegistryKey sk = rk.OpenSubKey(skName))
            {
              try
              {
                //If the key has value, continue, if not, skip it:
                if (!(sk.GetValue("DisplayName") == null))
                {
                  if (sk.GetValue("DisplayName").ToString().StartsWith(productName))
                  {
                    return true;
                  }
                }
              }
              catch (Exception)
              {
              }
            }
          }
        }
      }
      catch (Exception)
      {
      }
      return false;
    }


    private void button1_Click(object sender, EventArgs e)
    {
      /*
       * ProductName, ProductCode, UpgradeCode, Manufacturer, ARPHELPLINK, ARPCOMMENTS, ARPCONTACT, ARPURLINFOABOUT and ARPURLUDATEINFO
       * */
    }

    private void wizardControl1_CancelButtonClick(object sender, EventArgs e)
    {
      Close();
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void wizardControl1_FinishButtonClick(object sender, EventArgs e)
    {
      Close();
    }


    public void licenseCheck()
    {
      if (wizardControl1.CurrentStepIndex == wizardControl1.WizardSteps.IndexOf(licenceStep1) && (licenceStep1.Accepted == null || !licenceStep1.Accepted.Value))
        wizardControl1.NextButton.Enabled = false;
      else wizardControl1.NextButton.Enabled = true;
    }

    private void startStep1_Click(object sender, EventArgs e)
    {

    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
      try
      {
        if (Directory.Exists(htmlPageDir))
        {
          Directory.Delete(htmlPageDir, true);
        }
      }
      catch (Exception)
      {
      }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            ExtractContents();

            CheckInstalledVSVersions();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private void CheckInstalledVSVersions()
    {
      checkBox_VS2008.Enabled = false;
      checkBox_VS2010.Enabled = false;
      checkBox_VS2008.Checked = false;
      checkBox_VS2010.Checked = false;
      try
      {
        RegistryKey vs2008key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\9.0\Packages\{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}");
        if (vs2008key != null)
        {
          checkBox_VS2008.Enabled = true;
          checkBox_VS2008.Checked = true;
        }
      }
      catch { }
      try
      {
        RegistryKey vs2010key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\10.0\Packages\{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}");
        if (vs2010key != null)
        {
          checkBox_VS2010.Enabled = true;
          checkBox_VS2010.Checked = true;
        }
      }
      catch { }
    }

    internal string GetTempInstallerPath()
    {
      string folderName = "SPSFInstaller" + GetFileVersion().Replace(".", "_");
      return Path.Combine(Path.GetTempPath(), folderName);
    }

    private void ExtractContents()
    {
      try
      {
        htmlPageDir = GetTempInstallerPath();
        if (!Directory.Exists(htmlPageDir))
        {
          Directory.CreateDirectory(htmlPageDir);
        }

        Assembly assembly = Assembly.GetExecutingAssembly();

        //extract all html pages
        foreach (string s in assembly.GetManifestResourceNames())
        {
          if (s.StartsWith("SPALM.SharePointSoftwareFactory.SetupHelper.HTML"))
          {
            Stream stream = assembly.GetManifestResourceStream(s);
            byte[] raw = new byte[stream.Length];
            stream.Read(raw, 0, (int)stream.Length);

            string resourceFilename = s.Substring(string.Intern("SPALM.SharePointSoftwareFactory.SetupHelper.HTML").Length + 1);
            string saveToFilename = Path.Combine(htmlPageDir, resourceFilename);

            using (FileStream fstream = new FileStream(saveToFilename, FileMode.Create))
            {
              fstream.Write(raw, 0, (int)stream.Length);
            }
          }
        }

        //find the file in the assembly
        foreach (string s in assembly.GetManifestResourceNames())
        {
          if (s.Contains(".SetupFiles."))
          {
            string realName = s.Substring(string.Intern("SPALM.SharePointSoftwareFactory.SetupHelper.SetupFiles").Length + 1);
            Stream stream = assembly.GetManifestResourceStream(s);
            byte[] raw = new byte[stream.Length];
            stream.Read(raw, 0, (int)stream.Length);
            string saveToFilename = Path.Combine(htmlPageDir, realName);
            using (FileStream fstream = new FileStream(saveToFilename, FileMode.Create))
            {
              fstream.Write(raw, 0, (int)stream.Length);
            }
          }
        }


        this.webBrowser1.Url = new Uri(htmlPageDir + "\\readme.html");
      }
      catch (Exception)
      {
      }
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
      if (!checkBox_VS2008.Checked && !checkBox_VS2010.Checked)
      {
        this.wizardControl1.NextButtonEnabled = false;
      }
      else
      {
        this.wizardControl1.NextButtonEnabled = true;
      }
    }

    private void timer_Closing_Tick(object sender, EventArgs e)
    {
      this.Close();
    }
  }

  public class InstalledSoftware
  {
    public string ProductName = "";
    public string ProductVersion = "";
    public string ProductDescription = "";
  }
}
